package com.irdstudio.efp.e4a.service.impl;

import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.irdstudio.efp.e4a.common.constant.RuleTypeConstant;
import com.irdstudio.efp.e4a.service.dao.SRuleCollDao;
import com.irdstudio.efp.e4a.service.dao.SRuleCollDtlDao;
import com.irdstudio.efp.e4a.service.dao.SRuleCollDtlParamDao;
import com.irdstudio.efp.e4a.service.domain.SRuleColl;
import com.irdstudio.efp.e4a.service.domain.SRuleCollDtl;
import com.irdstudio.efp.e4a.service.domain.SRuleCollDtlParam;
import com.irdstudio.efp.e4a.service.facade.SRuleCollService;
import com.irdstudio.efp.e4a.service.vo.SRuleCollVO;
import com.irdstudio.basic.framework.core.base.AbstractFrameworkService;
import com.irdstudio.basic.framework.core.base.DataOptionalAuthorityDao;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.SequenceConstance;

/**
 * <p>
 * ServiceImpl: 系统规则集表
 * <p>
 * 
 * @author Cytus_
 * @date 2018-05-03
 */
@Service("sRuleCollService")
public class SRuleCollServiceImpl extends AbstractFrameworkService implements SRuleCollService, FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(SRuleCollServiceImpl.class);
	/** 省级法人机构码 */
	public static final String LEGAL_ORG_PROVINCIAL = "00001";
	private static final String YES = "1";
	private static final String NO = "2";
	/** 没有限制的规则集 */
	private static final String[] NO_LIMIT = { RuleTypeConstant.ADMITTANCE, RuleTypeConstant.RISK, RuleTypeConstant.CREDIT_CALC,
			RuleTypeConstant.INCREASE_ADMIT, RuleTypeConstant.INCREASE_CREDIT_CALC };
	@Autowired
	private SRuleCollDao sRuleCollDao;

	@Autowired
	private SRuleCollDtlDao sRuleCollDtlDao;

	@Autowired
	private SRuleCollDtlParamDao sRuleCollDtlParamDao;

	/**
	 * 新增操作
	 */
	@Override
	public int insertSRuleColl(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前新增数据为:" + inSRuleCollVo.toString());
		int num = 0;
		try {
			SRuleColl sRuleColl = new SRuleColl();
			num = valiSRuleCollData(inSRuleCollVo);
			if (num == 0 || num == -3) {
				String rulCollId = this.getSequence(SequenceConstance.RULE_COLL_SEQ_ID);
				inSRuleCollVo.setRuleCollId(rulCollId);
				beanCopy(inSRuleCollVo, sRuleColl);
				num = sRuleCollDao.insertSRuleColl(sRuleColl);
			}
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		return num;
	}

	/**
	 * 删除操作
	 */
	@Override
	public int deleteByPk(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前删除数据条件为:" + inSRuleCollVo);
		int num = 0;
		try {
			SRuleColl sRuleColl = new SRuleColl();
			beanCopy(inSRuleCollVo, sRuleColl);
			sRuleCollDtlParamDao.deleteByCollId(inSRuleCollVo.getRuleCollId());
			sRuleCollDtlDao.deleteByCollId(inSRuleCollVo.getRuleCollId());
			num = sRuleCollDao.deleteByPk(sRuleColl);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inSRuleCollVo + "删除的数据条数为" + num);
		return num;
	}

	/**
	 * 更新操作
	 */
	@Override
	public int updateByPk(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前修改数据为:" + inSRuleCollVo.toString());
		int num = 0;
		try {
			SRuleColl sRuleColl = new SRuleColl();
			beanCopy(inSRuleCollVo, sRuleColl);
			num = sRuleCollDao.updateByPk(sRuleColl);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inSRuleCollVo + "修改的数据条数为" + num);
		return num;
	}

	/**
	 * 查询操作
	 */
	@Override
	public SRuleCollVO queryByPk(SRuleCollVO inSRuleCollVo) {

		logger.debug("当前查询参数信息为:" + inSRuleCollVo);
		try {
			SRuleColl querySRuleColl = new SRuleColl();
			beanCopy(inSRuleCollVo, querySRuleColl);
			SRuleColl queryRslSRuleColl = sRuleCollDao.queryByPk(querySRuleColl);
			if (Objects.nonNull(queryRslSRuleColl)) {
				SRuleCollVO outSRuleCollVo = beanCopy(queryRslSRuleColl, new SRuleCollVO());
				logger.debug("当前查询结果为:" + outSRuleCollVo.toString());
				return outSRuleCollVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}

	/**
	 * 查询用户权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SRuleCollVO> queryAllOwner(SRuleCollVO sRuleCollVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		SRuleColl sRuleColl = beanCopy(sRuleCollVo, new SRuleColl());
		List<SRuleCollVO> list = null;
		try {
			List<SRuleColl> sRuleColls = sRuleCollDao.queryAllOwnerByPage(sRuleColl);
			logger.debug("当前查询本人所属数据信息的结果集数量为:" + sRuleColls.size());
			pageSet(sRuleColls, sRuleColl);
			list = (List<SRuleCollVO>) beansCopy(sRuleColls, SRuleCollVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SRuleCollVO> queryAllCurrOrg(SRuleCollVO sRuleCollVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		SRuleColl sRuleColl = beanCopy(sRuleCollVo, new SRuleColl());
		List<SRuleColl> sRuleColls = sRuleCollDao.queryAllCurrOrgByPage(sRuleColl);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + sRuleColls.size());
		List<SRuleCollVO> list = null;
		try {
			pageSet(sRuleColls, sRuleColl);
			list = (List<SRuleCollVO>) beansCopy(sRuleColls, SRuleCollVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SRuleCollVO> queryAllCurrDownOrg(SRuleCollVO sRuleCollVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		SRuleColl sRuleColl = beanCopy(sRuleCollVo, new SRuleColl());
		List<SRuleColl> sRuleColls = sRuleCollDao.queryAllCurrDownOrgByPage(sRuleColl);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + sRuleColls.size());
		List<SRuleCollVO> list = null;
		try {
			pageSet(sRuleColls, sRuleColl);
			list = (List<SRuleCollVO>) beansCopy(sRuleColls, SRuleCollVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	@Override
	public SRuleCollVO insertSRuleCollBack(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前新增数据为:" + inSRuleCollVo.toString());
		int num = 0;
		try {
			SRuleColl sRuleColl = new SRuleColl();
			num = valiSRuleCollData(inSRuleCollVo);
			if (num == 0 || num == -3) {
				String rulCollId = this.getSequence(SequenceConstance.RULE_COLL_SEQ_ID);
				inSRuleCollVo.setRuleCollId(rulCollId);
				beanCopy(inSRuleCollVo, sRuleColl);
				num = sRuleCollDao.insertSRuleColl(sRuleColl);
			}
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		inSRuleCollVo.setTotal(num); // 当作一个是否成功的标识
		return inSRuleCollVo;
	}

	@Override
	public int submitSRuleColl(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前修改数据为:" + inSRuleCollVo.toString());
		int num = 0;
		try {
			List<SRuleCollDtlParam> params = sRuleCollDtlParamDao.queryAllsByRuleCollId(inSRuleCollVo.getRuleCollId());
			if (null != params && params.size() > 0) {
				for (SRuleCollDtlParam param : params) {
					// 如果存在参数,但未配置值, 则提示 存在相关参数配置未完成
					if (null != param.getParamId() && (StringUtils.isEmpty(param.getParamVal())
							|| (null != param.getParamVal() && "".equals(param.getParamVal().trim())))) {
						num = -4;
						break;
					}
				}
			}
			int childCount = sRuleCollDtlDao.queryRuleCollDltCount(inSRuleCollVo.getRuleCollId());
			// 如果没有子规则，则不允许提交
			if (childCount == 0)
				num = -5;
			if (num == 0)
				num = valiSRuleCollData(inSRuleCollVo);
			if (num == 0) {

				SRuleColl sRuleColl = new SRuleColl();
				setInsertDefaultProperty(inSRuleCollVo);
				beanCopy(inSRuleCollVo, sRuleColl);
				num = sRuleCollDao.submitSRuleColl(sRuleColl);
			}
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inSRuleCollVo + "修改的数据条数为" + num);
		return num;
	}

	@Override
	public int disableSRuleColl(SRuleCollVO inSRuleCollVo) {
		logger.debug("当前修改数据为:" + inSRuleCollVo.toString());
		int num = 0;
		try {
			SRuleColl sRuleColl = new SRuleColl();
			setInsertDefaultProperty(inSRuleCollVo);
			beanCopy(inSRuleCollVo, sRuleColl);
			// 只能创建的人失效
			num = sRuleCollDao.disableSRuleColl(sRuleColl);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inSRuleCollVo + "修改的数据条数为" + num);
		return num;
	}

	private int valiSRuleCollData(SRuleCollVO inSRuleCollVo) {
		int num = 0;
		setInsertDefaultProperty(inSRuleCollVo);
		// 查询是否存在已经生效的规则配置(额度测算模型不限制)
		if (isLimit(inSRuleCollVo.getRuleCollType())) {
			num = sRuleCollDao.queryRuleTypeIsProvince(inSRuleCollVo);
			if (num > 0)
				num = -3;
		}
		if (LEGAL_ORG_PROVINCIAL.equals(inSRuleCollVo.getLoginUserLeageOrgCode())) {
			inSRuleCollVo.setIsProvince(YES);
		} else
			inSRuleCollVo.setIsProvince(NO);

		return num;
	}

	/** 规则集类型是否是限制的 */
	private boolean isLimit(String ruleType) {
		for (String type : NO_LIMIT) {
			if (type.equals(ruleType))
				return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SRuleCollVO> queryRuleCollByTypeLegal(SRuleCollVO sRuleCollVo) {

		logger.debug("当前查询本人所属机构和省级生效的规则集参数信息为:");
		List<SRuleCollVO> list = null;
		try {
			List<SRuleColl> sRuleColls = sRuleCollDao.queryRuleCollByTypeLegal(sRuleCollVo);
			logger.debug("当前查询本人所属机构和省级生效的规则集参数信息为:" + sRuleColls.size());
			list = (List<SRuleCollVO>) beansCopy(sRuleColls, SRuleCollVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public SRuleCollVO queryProvinceRuleCollByType(SRuleCollVO sRuleCollVo) {

		logger.debug("当前查询省级生效的规则集参数信息为:" + sRuleCollVo.getRuleCollType());
		SRuleCollVO result = null;
		try {
			List<SRuleColl> sRuleColls = sRuleCollDao.queryProvinceRuleCollByType(sRuleCollVo);
			logger.debug("当前查询省级生效的规则集参数信息为:" + sRuleColls.size());
			List<SRuleCollVO> list = (List<SRuleCollVO>) beansCopy(sRuleColls, SRuleCollVO.class);
			if (null != list && list.size() > 0)
				result = list.get(0);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return result;
	}

	@Override
	public int copyRuleCollById(SRuleCollVO sRuleCollVo) {
		logger.info("开始复制规则集!");
		int flag = 0;
		String ruleCollId = sRuleCollVo.getRuleCollId();
		String loginUserId = sRuleCollVo.getLoginUserId();
		String loginOrgCode = sRuleCollVo.getLoginUserOrgCode();
		SRuleColl sRuleColl = new SRuleColl();
		sRuleColl.setRuleCollId(ruleCollId);
		SRuleColl old = sRuleCollDao.queryByPk(sRuleColl);
		logger.info("复制的规则集内容:" + JSON.toJSONString(old));
		if (null != old) {
			try {
				List<SRuleCollDtl> oldDtls = sRuleCollDtlDao.queryAllByCollId(ruleCollId);
				List<SRuleCollDtlParam> oldDtlParams = sRuleCollDtlParamDao.queryAllsByRuleCollId(ruleCollId);
				SRuleColl rule = new SRuleColl();
				rule = beanCopy(old, rule);

				String neRuleCollId = this.getSequence(SequenceConstance.RULE_COLL_SEQ_ID);
				rule.setRuleCollId(neRuleCollId);
				rule.setLoginUserId(loginUserId);
				rule.setLoginUserOrgCode(loginOrgCode);
				rule.setLoginUserLeageOrgCode(sRuleCollVo.getLoginUserLeageOrgCode());
				rule.setRuleCollDesc(sRuleCollVo.getRuleCollDesc());
				setInsertDefaultProperty(rule);
				// 是否是省级配置
				if (LEGAL_ORG_PROVINCIAL.equals(rule.getLoginUserLeageOrgCode())) {
					rule.setIsProvince(YES);
				} else
					rule.setIsProvince(NO);
				String dtlId;
				String neDtlId;
				logger.info("复制规则集详细内容:" + JSON.toJSONString(oldDtls));
				// 复制规则集详细
				if (null != oldDtls && oldDtls.size() > 0) {
					for (SRuleCollDtl dtl : oldDtls) {
						// 修改 dtlId, 创建人(即:当前登录人)
						dtlId = dtl.getDtlId();
						neDtlId = this.getSequence(SequenceConstance.RULE_CFG_SEQ_ID);
						if (null != oldDtlParams && oldDtlParams.size() > 0) {
							for (SRuleCollDtlParam dtlParam : oldDtlParams) {
								if (dtlId.equals(dtlParam.getDtlId())) {
									dtlParam.setDtlId(neDtlId);
									dtlParam.setLoginUserId(loginUserId);
								}
							}
						}
						dtl.setRuleCollId(neRuleCollId);
						dtl.setDtlId(neDtlId);
						dtl.setLoginUserId(loginUserId);
					}
					flag += sRuleCollDao.insertSRuleColl(rule);
					flag += sRuleCollDtlDao.insertMoreRuleCollDtls(oldDtls);
					if (null != oldDtlParams && oldDtlParams.size() > 0)
						flag += sRuleCollDtlParamDao.insertMoreRuleCollDtlParams(oldDtlParams);

				}

			} catch (Exception e) {
				logger.error("复制规则集出现异常!!", e);
				flag = -1;
			}
		}

		return flag;
	}

	@Override
	public DataOptionalAuthorityDao getDataAuthorityDao() {
		return this.sRuleCollDao;
	}
}
